package cz.edukomplex.kosilka.client.content.block;

import java.util.ArrayList;

import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;

import cz.edukomplex.kosilka.client.helpers.MyRequestBuilder;
import cz.edukomplex.kosilka.client.helpers.MyXMLParser;
import cz.edukomplex.kosilka.client.model.QuestionModel;

public class QuestionPanel extends Composite {

	private static QuestionPanelUiBinder uiBinder = GWT
			.create(QuestionPanelUiBinder.class);

	interface QuestionPanelUiBinder extends UiBinder<Widget, QuestionPanel> {
	}
	
	@UiField VerticalPanel verticalPanel;
	
	@UiField Anchor back;
	
	@UiField Label subjectLabel;
	
	@UiField(provided = true)
	CellTable<QuestionModel> table;
	
	@UiField TextArea questionText;
	
	@UiField Button addQuestionButton;
	
	private int sid;
	private int Id_oboru;
	private String subjectName;
	private RequestBuilder rb;
	private ArrayList<QuestionModel> questionsList = new ArrayList<QuestionModel>();
	private SimplePanel parent;
	
	private static final ProvidesKey<QuestionModel> KEY_PROVIDER = new ProvidesKey<QuestionModel>() {

		@Override
		public Object getKey(QuestionModel item) {
			return item.getQid();
		}
	};
	
	public QuestionPanel(String subjectName,int sid,final int Id_oboru, final SimplePanel parent) {		
		
		table = new CellTable<QuestionModel>(KEY_PROVIDER);		
		initWidget(uiBinder.createAndBindUi(this));
		this.sid = sid;
		this.subjectName = subjectName;		
		this.Id_oboru = Id_oboru;
		this.parent = parent;	
						
		subjectLabel.setText(this.subjectName);	
		back.setHref("#");	
		
		rb = MyRequestBuilder.createService(RequestBuilder.POST, "Question", "fetchQuestionsBySid");
		try {
			rb.sendRequest("sid=" + this.sid,fetchQuestionsBySidCallback);
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initCellTable() {
		
		table.setPageSize(questionsList.size());
		
		// Cislo otazky
		TextColumn<QuestionModel> questoinNumberColumn = new TextColumn<QuestionModel>() {
			
			@Override
			public String getValue(QuestionModel object) {
				return "" + (new Integer(object.getQn()) + 1);//v databaze sa cisluje od 0, preto +1
			}
		};
		
		
		//Text otazky
		final Column<QuestionModel, String> questionTextColumn = new Column<QuestionModel, String>(new EditTextCell()) {
			
			@Override
			public String getValue(QuestionModel object) {
				return object.getText();
			}
		};
		questionTextColumn.setFieldUpdater(new FieldUpdater<QuestionModel, String>() {
			
			@Override
			public void update(int index, QuestionModel object, String value) {				
				
				if((value.length() < 1) || value.equals(object.getText())){
					EditTextCell cell = (EditTextCell)questionTextColumn.getCell();
					cell.clearViewData(KEY_PROVIDER.getKey(object));
					table.redraw();
					return;
				}
				
				rb = MyRequestBuilder.createService(RequestBuilder.POST, "Question", "editQuestionById");

				try {
					rb.sendRequest("qid=" + object.getQid() + "&text=" + value ,
							editQuestionByIdCallback
					);
				} catch (RequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
			}
		});		
		
		//Button  na odstranenie otazky
		Column<QuestionModel, String> removeButtonColumn = new Column<QuestionModel, String>(new ButtonCell()) {
			
			@Override
			public String getValue(QuestionModel object) {
				return "Zmazať";
			}
		};
		removeButtonColumn.setFieldUpdater(new FieldUpdater<QuestionModel, String>() {
			
			@Override
			public void update(int index, final QuestionModel object, String value) {
				
				rb = MyRequestBuilder.createService(RequestBuilder.POST, "Question", "deleteById");

				try {
					rb.sendRequest("qid=" + object.getQid(), new RequestCallback() {

						@Override
						public void onResponseReceived(Request request, Response response) {
							if(response.getText().equals("true")){
								questionsList.remove(object);
								refreshTable();
							}
							else {
								Window.alert("Otázku sa nepodarilo odstrániť");
							}

						}

						@Override
						public void onError(Request request, Throwable exception) {
							Window.alert("Otázku sa nepodarilo odstrániť");

						}
					});
				} catch (RequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
		
		table.addColumn(questoinNumberColumn, "#");
		table.addColumn(questionTextColumn, "Text");
		table.addColumn(removeButtonColumn);
		
		refreshTable();
	}

	private RequestCallback fetchQuestionsBySidCallback = new RequestCallback() {

		@Override
		public void onError(Request request, Throwable exception) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onResponseReceived(Request request, Response response) {
			parseXMLResponse(response.getText());
			initCellTable();
		}
	};

	
	private RequestCallback editQuestionByIdCallback = new RequestCallback() {

		@Override
		public void onResponseReceived(Request request, Response response) {
			if((response.getText()).equals("true")){
				//Window.alert("Ótázka zmenená");
			}
			else {				
				Window.alert("Nastala chyba pri ukladaní");
			}
			
		}

		@Override
		public void onError(Request request, Throwable exception) {
			Window.alert("Otázku sa nepodarilo zmeniť");

		}

	};
	
	@UiHandler("back")
	public void handleBackButton(ClickEvent e){		
		//parent.setWidget(new BlockContent("" + Id_oboru));
	}
	
	
	@UiHandler("addQuestionButton")
	public void handleAddQuestionButtonClick(ClickEvent e){
				
		final QuestionModel lastQuestion = questionsList.get(questionsList.size()-1);
		final String text = questionText.getText();

		if(text.isEmpty()){
			return;
		}
		
		final String questionNumber = "" + (new Integer(lastQuestion.getQn()) + 1);
		
		rb = MyRequestBuilder.createService(RequestBuilder.POST, "Question", "addQuestion");
		try {
			rb.sendRequest("qn=" + questionNumber + 
					"&sid=" + lastQuestion.getSid() +
					"&text=" + text, 
					 new RequestCallback() {

				@Override
				public void onResponseReceived(Request request, Response response) {
					
					if(response.getText().equals("false")){
						Window.alert(response.getText());
						return;
					}
					
					questionText.setText("");
					
					QuestionModel insertedModel = new QuestionModel(response.getText(), 
							lastQuestion.getSid(), 
							questionNumber, 
							text
					);
					
					questionsList.add(insertedModel);
					refreshTable();					
				}				

				@Override
				public void onError(Request request, Throwable exception) {
					Window.alert("Otázku sa nepodarilo pridať");			
				}
			});
			
			
		} catch (RequestException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
	}
	
	
	/**
	 * Text prevedie na XML a nasledne na objekty, ktore prida do 
	 * <code>ArrayList questionList</code>
	 * 
	 * @param String vo formate xml
	 */
	private void parseXMLResponse(String response){
				
		Element root = MyXMLParser.parseXML(response);
		NodeList questions = root.getElementsByTagName("question");
				
		for (int i = 0; i < questions.getLength(); i++) {
			Element question = (Element)questions.item(i);
			String questionText = question.getAttribute("text");
			String qid = question.getAttribute("qid");
			String qn = question.getAttribute("qn");
			String sid = question.getAttribute("sid");			
			questionsList.add(new QuestionModel(qid, sid, qn, questionText));			
		}
	}
	
	private void refreshTable() {
		table.setPageSize(questionsList.size());
		//Nastavnie poctu riadkov
		table.setRowCount(questionsList.size(), true);
	    // Obnovenie tabulky s novymi datami
	    table.setRowData(0, questionsList);					
	}
}
